package  com.diamond.action;

import java.io.File;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.diamond.bo.QueryUserBO;
import com.diamond.bo.ReturnBO;
import com.diamond.bo.SalesBO;
import com.diamond.bo.UserBO;
import com.diamond.entity.User;
import com.diamond.facade.UserFacade;
import com.diamond.util.JsonMSG;
import com.diamond.util.JsonUtils;
import com.diamond.util.MD5;
import com.diamond.util.StringUtil;
import com.diamond.util.UploadUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("unchecked")
public class UserAction extends ActionSupport {

	private static Logger log=LoggerFactory.getLogger(UserAction.class);
	
	private static final long serialVersionUID = -5414658843367321286L;
	private UserFacade userFacade;
	private UserBO userBo;
	private List<UserBO> dataList;
	private QueryUserBO queryUserBo;
	private String tips;
	private String json;
	private String logoFileName;
	private File logo;
	private String bpicFileName;
	private File bpic;
	private String spicFileName;
	private File spic;
	private String oldpass;
	private String subUserId;
	private String surepass;
	private String newPW;
	private List sales;
	private SalesBO salesBO;
	public void setUserFacade(UserFacade userFacade) {
		this.userFacade = userFacade;
	}
	
	public String loginOut() {
//		System.out.println("**************后台退出登录******************");
		Map session = ActionContext.getContext().getSession();
		this.removeUserBO(session);
		this.json=JsonMSG.sucess("用户已退出登录").toJson();
		return "json";
	}
	
	public String backLogin() {
//		System.out.println("**************后台用户登录******************");
		Map session = ActionContext.getContext().getSession();
		try {
			if (null != userBo && !"".equals(userBo.getUserName()) && !"".equals(userBo.getPassword()) && !"".equals(userBo.getRandCode())) {
				if ((userBo.getRandCode()).equals(session.get("rand"))) {
					userBo.setPassword(MD5.encode(userBo.getPassword()));
					List<UserBO> userBolist = userFacade.backLogin(userBo);
					if (userBolist.size() == 1) {
						this.setUserBO(session, userBolist.get(0));
						this.json=JsonMSG.sucess("用户登录成功").toJson();
					} else {
						this.json=JsonMSG.failed("用户名，密码错误，请重新输入！").toJson();
					}
				} else {
					this.json = JsonMSG.failed("验证码错误，请重新输入").toJson();
				}
			}
		} catch (Exception e) {
			this.json=JsonMSG.failed("用户登录失败!详细:" + e).toJson();
			e.printStackTrace();
		}
//		System.out.println(" 用户登录验证码为： " + ActionContext.getContext().getSession().get("rand"));
//		System.out.println("用户名：" + userBo.getUserName() + "   密码： "+ userBo.getPassword() + " 输入验证码为：" + userBo.getRandCode());
		return "json";
	}

	/**
	 * 添加和修改用户
	 * @return
	 * @throws Exception 
	 */
	public String addOrUpdateUser(){
		try {
			userBo=(UserBO) JsonUtils.toObject(json, UserBO.class);
			userFacade.addOrUpdateUser(userBo);
			this.json=JsonMSG.sucess("恭喜，操作成功!").toJson();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("添加用户出错",e);
			this.json=JsonMSG.failed("提示，操作失败"+e).toJson();
		}
			return "json";
	}
    /** 切换用户页面主题;*/
	public String changeTheme(){
    	ActionContext.getContext().getSession().put("theme", json);
    	return "json";
    }
    /**
     * 用户名验证
     */
    public String checkUsername(){
    	String userName = json;
    	Boolean result;
		try {
			result = userFacade.checkUserName(userName);
			if (result) {
	        	this.json=JsonMSG.sucess("恭喜您，该用户名可用!").toJson();
	    	} else {
	        	this.json=JsonMSG.failed("该用户名已存在，请您重新输入！").toJson();
	    	}
		} catch (Exception e) {
			e.printStackTrace();
			this.json=JsonMSG.failed("该用户名已存在，请您重新输入！").toJson();
			log.error("查询用户名出错",e);
		}
    	return "json";
    }
    
    /**
     * 删除用户
     * @return
     */
	public String doDelete() {
		try {
			String[] userIds = json.split(";");
			if (userIds.length > 0) {
				Boolean result = userFacade.deleteUser(userIds);
				if (result) 
					this.json=JsonMSG.sucess("用户已删除!").toJson();
			} else {
				this.json = JsonMSG.failed("请选择需要删除的用户！").toJson();
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.json=JsonMSG.failed("删除用户出错!详细:"+e).toJson();
			log.error("删除用户出错!详细:",e);
		}
			return "json";
	}

	/**
	 * 根据userType查询用户
	 */
	public String queryUserByUserType() {
		try {
			String userType = json;
			String[] userTypes = userType.split(":");
			List<UserBO> userBolist = userFacade.queryUserByUserType(userTypes);
			this.json=JsonMSG.sucess(userBolist).toJson();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("查询失败",e);
			this.json=JsonMSG.failed("查询失败！").toJson();
		}
		return "json";
	}
	
	/**
	 * 根据UserId查询用户详细信息
	 * @return
	 */
	public String findUserByUserId() {
		try {
			String userCode=json;
			UserBO returnUserBo = userFacade.findUserByUserId(userCode);
			this.json=JsonMSG.sucess(returnUserBo).toJson();
		} catch (Exception e) {
			e.printStackTrace();
			log.error("查询用户出错 ",e);
			this.json=JsonMSG.failed("系统未找到该 用户:"+json).toJson();
		}
		return "json";
	}
	
	/**
	 * 查询用户;
	 * @return
	 */
	public String queryUser() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String start = request.getParameter("start");
		String pageSize = request.getParameter("limit");
		try {
			if(null==json|| "".equals(json.trim())||"null".equals(json.toLowerCase())){//默认查询全部;
				queryUserBo=new QueryUserBO();
			}
			else{
				queryUserBo = (QueryUserBO) JsonUtils.toObject(json, QueryUserBO.class);
			}
			if (null == start || "".equals(start) || null == pageSize || "".equals(pageSize)) {
				queryUserBo.setStart(0);
				queryUserBo.setPageSize(100);
			} else {
				queryUserBo.setStart(Integer.valueOf(start));
				queryUserBo.setPageSize(Integer.valueOf(pageSize));
			}
			ReturnBO<UserBO> returnBo = userFacade.queryUser(queryUserBo);
			this.json=JsonMSG.sucess(returnBo).toJson();
		} catch (Exception e) {
			e.printStackTrace();
			this.json=JsonMSG.failed("查询失败").toJson();
			log.error("查询异常!",e);
		}
		return "json";
	}
	
	
	public String updateBackUserPW() {
		HttpServletRequest request = ServletActionContext.getRequest();
		Map session = ActionContext.getContext().getSession(); 
		Long userId=(Long) session.get("USER_ID");
		String userName = (String) session.get("USER_NAME");
		String oldPassword = MD5.encode(request.getParameter("oldPassword"));
		String newPassword = MD5.encode(request.getParameter("newPassword"));
		String surePassword = MD5.encode(request.getParameter("surePassword"));
		userBo=new UserBO();
		userBo.setUserName(userName);
		userBo.setPassword(oldPassword);
		try {
			if (newPassword.equals(surePassword)) {
				List<UserBO> userBolist = userFacade.backLogin(userBo);
				if (userBolist.size() == 1) {
					Boolean result = userFacade.updateBackUserPW(userId, oldPassword, newPassword);
					if (result) {
						this.json=JsonMSG.sucess("修改成功，请记住新密码！").toJson();
					} else {
						this.json = JsonMSG.failed("密码修改失败！").toJson();
					}
				} else {
					this.json = JsonMSG.failed("原始密码输入错误，请重新输入！").toJson();
				}
			} else {
				this.json = JsonMSG.failed("新密码两次输入不一致，请重新输入！").toJson();
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.json = JsonMSG.failed("密码修改失败！").toJson();
			log.error("查询异常!",e);
		}
		return "json";
	}

    public void setUserBO(Map session,UserBO bo){
    	session.put("USER_ID", bo.getUserId());
    	if(bo.getParentAgentId()!=null&&bo.getParentAgentId()!=0)
    	session.put("ANGENT_ID", bo.getParentAgentId()); 
    	session.put("USER_TYPE", bo.getUserType()); 
    	session.put("USER_NAME", bo.getUserName()); 
    	if(!StringUtil.isEmpty(bo.getLogo()))
    		session.put("USER_LOGO", bo.getLogo());
    	if(!StringUtil.isEmpty(bo.getBigPic()))
    		session.put("USER_BPIC", bo.getBigPic()); 
    	if(!StringUtil.isEmpty(bo.getSmallPic()))
    		session.put("USER_SPIC", bo.getSmallPic()); 
    }
    public void removeUserBO(Map session){
    	session.remove("USER_ID");
    	session.remove("ANGENT_ID");
    	session.remove("USER_NAME");
    	session.remove("USER_LOGO");
    	session.remove("USER_BPIC");
    	session.remove("USER_SPIC");
    }

/*-------------------------------------------------------------------------------------------------------------------*/
	/**
	 * 前台用户登录;
	 * @return
	 */
	public String tologin(){
		return SUCCESS;
	}
	/**
	 * 跳转到用户信息页面;
	 * @return
	 */
	public String toUser(){
		Map session = ActionContext.getContext().getSession(); 
	    Long id=(Long) session.get("USER_ID");
	    User myuser=(User) userFacade.findById(id);
	    userBo=new UserBO();
	    try {
			PropertyUtils.copyProperties(userBo, myuser);
			List<UserBO> subUserBolist = userFacade.searchSubUser(id);
			this.setDataList(subUserBolist);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return SUCCESS;
	}
	/**
	 * 修改密码;
	 * @return
	 */
	public String upPass() {
		json = JsonMSG.failed("更新错误.").toJson();
		if (!StringUtil.isEmpty(oldpass) && !StringUtil.isEmpty(surepass)) {
			json = JsonMSG.failed("密码错误.").toJson();
			String encode = MD5.encode(oldpass);
			Map session = ActionContext.getContext().getSession();
			Long id = (Long) session.get("USER_ID");
			User myuser = (User) userFacade.findById(id);
			userBo = new UserBO();
			try {
				PropertyUtils.copyProperties(userBo, myuser);
				if (encode.equals(userBo.getPassword())) {
					userBo.setPassword(MD5.encode(surepass));
					userFacade.updateUser(userBo);
					json = JsonMSG.sucess("更新成功.").toJson();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return SUCCESS;
	}
	
	/**
	 * 修改子用户密码;
	 * @return
	 */
	public String upSonPass() {
		json = JsonMSG.failed("更新错误.").toJson();
//		System.out.print(subUserId);
		if (!StringUtil.isEmpty(surepass)) {
			Map session = ActionContext.getContext().getSession();
			Long id = (Long) session.get("USER_ID");
			if ("0".equals(subUserId)) {
				userFacade.updateSonPass(id,surepass);
			} else {
				userFacade.updateSonPassByUserId(Long.valueOf(subUserId),surepass);
			}
			json = JsonMSG.sucess("更新成功.").toJson();
		}
		return SUCCESS;
	}
	/**
	 * 修改用户;
	 * @return
	 */
	public String upUser(){
		tips="更新失败.";
		Map session = ActionContext.getContext().getSession(); 
		if(!StringUtil.isEmpty(logoFileName)){
			String[] disfileName=UploadUtil.getExtention(logoFileName,"logo",session.get("USER_ID")+"_logo");
			File imageFile = new File(disfileName[1]);
			UploadUtil.copy(logo, imageFile);
			userBo.setLogo(disfileName[0]);
			session.put("USER_LOGO", userBo.getLogo());
		}
		if(!StringUtil.isEmpty(bpicFileName)){
			String[] disfileName=UploadUtil.getExtention(bpicFileName,"logo",session.get("USER_ID")+"_bpic");
			File imageFile = new File(disfileName[1]);
			UploadUtil.copy(bpic, imageFile);
			userBo.setBigPic(disfileName[0]);
			session.put("USER_BPIC", userBo.getBigPic()); 
		}
		if(!StringUtil.isEmpty(spicFileName)){
			String[] disfileName=UploadUtil.getExtention(spicFileName,"logo",session.get("USER_ID")+"_spic");
			File imageFile = new File(disfileName[1]);
			UploadUtil.copy(spic, imageFile);
			userBo.setSmallPic(disfileName[0]);
			session.put("USER_SPIC", userBo.getSmallPic()); 
		}
		userFacade.updateUser(userBo);
		tips="更新成功.";
		return SUCCESS;
	}
	/**
	 * 前台用户登录用户中心;
	 * @return
	 */
	public String toLoginCenter(){
		return SUCCESS;
	}
	/**
	 * 用户登陆到用户中心;
	 * @return
	 */
	public String logInCenter(){
		User bo =userFacade.loginCenter(userBo);
		if(bo!=null){
			ActionContext.getContext().getSession().put("USER_CENTER", "true");
			setUser(bo);
			return SUCCESS;
		}else{
			tips="用户未被允许访问.";
			return INPUT;
		}
		
	}
	/**
	 * 用户注销用户中心;
	 * @return
	 */
	public String logOutCenter(){
		Map session = ActionContext.getContext().getSession(); 
		ActionContext.getContext().getSession().remove("USER_CENTER");
		return SUCCESS;
	}
	
	/**
	 * 用户登陆;
	 * @return
	 */
	public String login() {
		// 大连总代理指定验证码AGT_DL01
		String trueCode = (String) ServletActionContext.getRequest().getSession().getAttribute(
						com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		String myCode = ServletActionContext.getRequest().getParameter("mycode");
		if (!"AGT_DL01".equals(myCode)) {
			if (myCode == null || !trueCode.equalsIgnoreCase(myCode)) {
				tips = "验证码错误.";
				return INPUT;
			}
		}
		User bo = userFacade.login(userBo);
		if (bo != null) {
			setUser(bo);
			return SUCCESS;
		} else {
			tips = "用户名或密码错误，请重新输入.";
			return INPUT;
		}
	}
	/**
	 * 用户注销;
	 * @return
	 */
	public String logout(){
		Map session = ActionContext.getContext().getSession(); 
		removeUser(session);
		return SUCCESS;
	}
	/**
	 * 代理商查看销售额;
	 * @return
	 */
	public String toSales(){
		Map session = ActionContext.getContext().getSession(); 
	    Long userId=(Long) session.get("USER_ID");
	    String userType=(String) session.get("USER_TYPE");
	    if("B".equals(userType))sales=userFacade.getSales(userId,salesBO);
		return SUCCESS;
	}
	/**
	 * 储存session信息;
	 * @return
	 */
    public void setUser(User bo){
    	Map session = ActionContext.getContext().getSession(); 
    	session.put("USER_ID", bo.getUserId()); 
    	session.put("CMP_NAME", bo.getCmpName()); 
    	if(bo.getParentAgentId()!=null&&bo.getParentAgentId()!=0)
    	session.put("ANGENT_ID", bo.getParentAgentId()); 
    	session.put("USER_TYPE", bo.getUserType()); 
    	session.put("USER_NAME", bo.getUserName()); 
    	if(!StringUtil.isEmpty(bo.getLogo()))session.put("USER_LOGO", bo.getLogo());
    	if(bo.getLogoWidth()!=null)session.put("USER_LOGO_WIDTH", bo.getLogoWidth());
    	if(bo.getLogoHeight()!=null)session.put("USER_LOGO_HEIGHT", bo.getLogoHeight());
    	if(!StringUtil.isEmpty(bo.getBigPic()))session.put("USER_BPIC", bo.getBigPic()); 
    	if(!StringUtil.isEmpty(bo.getSmallPic()))session.put("USER_SPIC", bo.getSmallPic()); 
    }
	/**
	 * 移除session信息;
	 * @return
	 */
    public void removeUser(Map session){
    	session.remove("USER_ID");
    	session.remove("CMP_NAME");
    	session.remove("ANGENT_ID");
    	session.remove("USER_CENTER");
    	session.remove("USER_TYPE");
    	session.remove("USER_NAME");
    	session.remove("USER_LOGO");
    	session.remove("USER_BPIC");
    	session.remove("USER_SPIC");
    }
    /*-------------------------------------------------------------------------------------------------------------------*/
	public List<UserBO> getDataList() {
		return dataList;
	}

	public void setDataList(List<UserBO> dataList) {
		this.dataList = dataList;
	}
 
	public UserBO getUserBo() {
		return userBo;
	}

	public void setUserBo(UserBO userBo) {
		this.userBo = userBo;
	}

	public UserBO getUser() {
		return userBo;
	}

	public void setUser(UserBO userBo) {
		this.userBo = userBo;
	}
    
	public String getTips() {
		return tips;
	}

	public void setTips(String tips) {
		this.tips = tips;
	}
	
	public QueryUserBO getQueryUserBo() {
		return queryUserBo;
	}

	public void setQueryUserBo(QueryUserBO queryUserBo) {
		this.queryUserBo = queryUserBo;
	}
	
	public String getJson() {
		return json;
	}

	public void setJson(String json) {
		this.json = json;
	}

	public File getLogo() {
		return logo;
	}

	public void setLogo(File logo) {
		this.logo = logo;
	}

	public String getLogoFileName() {
		return logoFileName;
	}

	public void setLogoFileName(String logoFileName) {
		this.logoFileName = logoFileName;
	}

	public String getBpicFileName() {
		return bpicFileName;
	}

	public void setBpicFileName(String bpicFileName) {
		this.bpicFileName = bpicFileName;
	}

	public File getBpic() {
		return bpic;
	}

	public void setBpic(File bpic) {
		this.bpic = bpic;
	}

	public String getSpicFileName() {
		return spicFileName;
	}

	public void setSpicFileName(String spicFileName) {
		this.spicFileName = spicFileName;
	}

	public File getSpic() {
		return spic;
	}

	public void setSpic(File spic) {
		this.spic = spic;
	}

	public String getOldpass() {
		return oldpass;
	}

	public void setOldpass(String oldpass) {
		this.oldpass = oldpass;
	}

	public String getSurepass() {
		return surepass;
	}

	public void setSurepass(String surepass) {
		this.surepass = surepass;
	}

	public List getSales() {
		return sales;
	}

	public void setSales(List sales) {
		this.sales = sales;
	}

	public SalesBO getSalesBO() {
		return salesBO;
	}

	public void setSalesBO(SalesBO salesBO) {
		this.salesBO = salesBO;
	}

	public String getNewPW() {
		return newPW;
	}

	public void setNewPW(String newPW) {
		this.newPW = newPW;
	}

	public String getSubUserId() {
		return subUserId;
	}

	public void setSubUserId(String subUserId) {
		this.subUserId = subUserId;
	}
}
